<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { useToast } from "primevue/usetoast";
import { authApi } from "../../api/auth.js";
import { useRouter } from "vue-router";
import { useAuth } from "../../composables/useAuth.js";

const router = useRouter();
// 响应式数据
const showDialog = ref(false);
const isLoginMode = ref(true);
const loading = ref(false);
const isLoggedIn = ref(false);
const userInfo = ref({});

const toast = useToast();

// 登录表单
const loginForm = reactive({
  username: "",
  password: "",
});

// 注册表单
const registerForm = reactive({
  username: "",
  password: "",
  realName: "",
  phone: "",
  age: null,
  city: null,
  gender: 0,
});

// 重置表单
const resetForm = () => {
  // 重置登录表单
  loginForm.username = "";
  loginForm.password = "";

  // 重置注册表单
  registerForm.username = "";
  registerForm.password = "";
  registerForm.realName = "";
  registerForm.phone = "";
  registerForm.age = null;
  registerForm.city = null;
  registerForm.gender = 0;
};

// 验证登录表单
const validateLoginForm = () => {
  let isValid = true;

  if (!loginForm.username.trim()) {
    toast.add({
      severity: "error",
      summary: "登录失败",
      detail: "用户名不能为空",
      life: 3000,
    });
    return;
  }

  if (!loginForm.password.trim()) {
    toast.add({
      severity: "error",
      summary: "登录失败",
      detail: "密码不能为空",
      life: 3000,
    });
    return;
  }

  return isValid;
};

// 验证注册表单
const validateRegisterForm = () => {
  let isValid = true;
  if (!registerForm.username.trim()) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "用户名不能为空",
      life: 3000,
    });
    return;
  }

  if (!registerForm.password.trim()) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "密码不能为空",
      life: 3000,
    });
    return;
  } else if (registerForm.password.length < 6) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "密码长度不能少于6位",
      life: 3000,
    });
    return;
  }

  if (!registerForm.realName.trim()) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "真实姓名不能为空",
      life: 3000,
    });
    return;
  }

  if (registerForm.phone && !/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "手机号格式不正确",
      life: 3000,
    });
    return;
  }

  if (!registerForm.age) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "年龄不能为空",
      life: 3000,
    });
    return;
  }

  if (!registerForm.city) {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: "城市不能为空",
      life: 3000,
    });
    return;
  }

  return isValid;
};

// 处理登录
const handleLogin = async () => {
  if (!validateLoginForm()) return;
  loading.value = true;
  const res = await authApi.login({
    username: loginForm.username,
    password: loginForm.password,
  });
  if (res.success) {
    // 使用新的认证系统
    const { setUser, setToken } = useAuth();
    setToken(res.data.token);
    setUser(res.data);
    
    // 保持原有的状态管理
    sessionStorage.setItem("pmp-token", res.data.token);
    sessionStorage.setItem("pmp-userInfo", JSON.stringify(res.data));
    userInfo.value = res.data;
    isLoggedIn.value = true;
    showDialog.value = false;
    toast.add({
      severity: "success",
      summary: "登录成功",
      detail: "欢迎回来！",
      life: 3000,
    });
    loading.value = false;
    if (res.data.username === 'admin') {
      router.push('/backstage/pmpu')
    }
  } else {
    toast.add({
      severity: "error",
      summary: "登录失败",
      detail: res.message,
      life: 3000,
    });
  }
  loading.value = false;
};

// 处理注册
const handleRegister = async () => {
  if (!validateRegisterForm()) return;
  loading.value = true;
  const res = await authApi.register({
    username: registerForm.username,
    password: registerForm.password,
    realName: registerForm.realName,
    phone: registerForm.phone,
    age: registerForm.age,
    city: registerForm.city,
    gender: registerForm.gender,
  });
  if (res.success) {
    toast.add({
      severity: "success",
      summary: "注册成功",
      detail: "注册成功，请登录",
      life: 3000,
    });
    showDialog.value = false;
  } else {
    toast.add({
      severity: "error",
      summary: "注册失败",
      detail: res.message,
      life: 3000,
    });
  }
  loading.value = false;
};

const menu = ref();
// 处理退出登录
const handleLogout = async () => {
  await authApi.logout();
  sessionStorage.removeItem("pmp-token");
  sessionStorage.removeItem("pmp-userInfo");
  sessionStorage.removeItem("userAnswerId-pmpu");
  sessionStorage.removeItem("isTestFinished-pmpu");
  sessionStorage.removeItem("userAnswerGroupId-pmpu");
  sessionStorage.removeItem("userAnswerGroupId");
  sessionStorage.removeItem("isTestFinished");
  sessionStorage.removeItem("currentQuestionnaireIndex");
  sessionStorage.removeItem("isStartTest");

  isLoggedIn.value = false;
  userInfo.value = {};
  toast.add({
    severity: "success",
    summary: "退出成功",
    detail: "已安全退出登录",
    life: 3000,
  });
};
const items = ref([
  {
    label: "安全退出",
    icon: "pi pi-sign-out",
    command: () => {
      handleLogout();
    },
  },
]);
const toggle = (event) => {
  menu.value.toggle(event);
};

onMounted(() => {
  const token = sessionStorage.getItem("pmp-token");
  if (token) {
    isLoggedIn.value = true;
    userInfo.value = JSON.parse(sessionStorage.getItem("pmp-userInfo"));
  }
});
</script>

<template>
  <div>
    <!-- 触发按钮 -->
    <div v-if="!isLoggedIn" class="flex border-round surface-border">
      <Button
        :label="'登录'"
        :class="isLoginMode ? 'p-button-primary' : 'p-button-text'"
        @click="
          () => {
            isLoginMode = true;
            showDialog = true;
          }
        "
        class="border-round-left"
        size="small"
      />
      <Button
        :label="'注册'"
        :class="!isLoginMode ? 'p-button-primary' : 'p-button-text'"
        @click="
          () => {
            isLoginMode = false;
            showDialog = true;
          }
        "
        class="border-round-right"
        size="small"
      />
    </div>
    <div v-else>
      <div class="flex items-center cursor-pointer gap-2" @click="toggle">
        <Avatar
          icon="pi pi-user"
          :style="{
            backgroundColor:
              userInfo?.gender === 1
                ? '#87CEEB'
                : userInfo?.gender === 2
                ? '#FFB6C1'
                : '#D3D3D3',
            color: '#fff',
          }"
          shape="circle"
        />
        <div class="text-sm">{{ userInfo?.realName || "用户" }}</div>
      </div>
      <Menu
        ref="menu"
        :model="items"
        :popup="true"
        :pt="{
          root: { style: 'min-width: 10rem; width: 10rem;' },
        }"
      />
    </div>
    <!-- 登录/注册对话框 -->
    <Dialog
      v-model:visible="showDialog"
      :header="isLoginMode ? '用户登录' : '用户注册'"
      modal
      :style="{ width: '450px' }"
      :closable="true"
      @hide="resetForm"
    >
      <div class="flex flex-col gap-4">
        <!-- 登录表单 -->
        <form
          v-if="isLoginMode"
          @submit.prevent="handleLogin"
          class="flex flex-col gap-4"
        >
          <FloatLabel variant="on" class="mt-4">
            <IconField>
              <InputIcon class="pi pi-user" />
              <InputText
                id="login-username"
                v-model="loginForm.username"
                class="w-full"
                maxlength="20"
              />
            </IconField>
            <label for="login-username">用户名</label>
          </FloatLabel>
          <FloatLabel variant="on">
            <IconField>
              <InputIcon class="pi pi-lock" />
              <Password
                id="login-password"
                v-model="loginForm.password"
                :feedback="false"
                toggleMask
                class="w-full"
                maxlength="16"
              />
            </IconField>
            <label for="login-password">密码</label>
          </FloatLabel>
          <Button
            type="submit"
            label="登录"
            icon="pi pi-sign-in"
            :loading="loading"
            class="w-full mt-10"
          />
        </form>

        <!-- 注册表单 -->
        <form
          v-else
          @submit.prevent="handleRegister"
          class="flex flex-col gap-4"
        >
          <FloatLabel variant="on" class="mt-4">
            <IconField>
              <InputIcon class="pi pi-user" />
              <InputText
                id="register-username"
                v-model="registerForm.username"
                class="w-full"
                maxlength="20"
              />
            </IconField>
            <label for="register-username">用户名</label>
          </FloatLabel>
          <FloatLabel variant="on">
            <IconField>
              <InputIcon class="pi pi-lock" />
              <Password
                id="register-password"
                v-model="registerForm.password"
                toggleMask
                class="w-full"
                maxlength="16"
                :feedback="false"
              />
            </IconField>
            <label for="register-password">密码</label>
          </FloatLabel>

          <FloatLabel variant="on">
            <IconField>
              <InputIcon class="pi pi-id-card" />
              <InputText
                id="register-realName"
                v-model="registerForm.realName"
                class="w-full"
                maxlength="20"
              />
            </IconField>
            <label for="register-realName">真实姓名</label>
          </FloatLabel>

          <FloatLabel variant="on">
            <IconField>
              <InputIcon class="pi pi-phone" />
              <InputText
                id="register-phone"
                v-model="registerForm.phone"
                class="w-full"
                maxlength="11"
              />
            </IconField>
            <label for="register-phone">手机号</label>
          </FloatLabel>

          <FloatLabel variant="on">
            <IconField>
              <InputIcon class="pi pi-calendar" />
              <InputNumber
                id="register-age"
                v-model="registerForm.age"
                class="w-full"
                :min="1"
                :max="120"
              />
            </IconField>
            <label for="register-age">年龄</label>
          </FloatLabel>

          <FloatLabel variant="on">
            <IconField>
              <InputIcon class="pi pi-map-marker" />
              <InputText
                type="text"
                class="w-full"
                v-model="registerForm.city"
              />
            </IconField>
            <label for="register-city">城市</label>
          </FloatLabel>

          <div class="flex gap-3">
            <!-- <div class="flex align-items-center">
              <RadioButton
                v-model="registerForm.gender"
                :value="0"
                inputId="gender-unknown"
              />
              <label for="gender-unknown" class="ml-2 text-purple-500"
                >保密</label
              >
            </div> -->
            <div class="flex align-items-center">
              <RadioButton
                v-model="registerForm.gender"
                :value="1"
                inputId="gender-male"
              />
              <label for="gender-male" class="ml-2 text-blue-500">
                <i class="pi pi-mars mr-1"></i>男
              </label>
            </div>
            <div class="flex align-items-center">
              <RadioButton
                v-model="registerForm.gender"
                :value="2"
                inputId="gender-female"
              />
              <label for="gender-female" class="ml-2 text-pink-500">
                <i class="pi pi-venus mr-1"></i>女
              </label>
            </div>
          </div>

          <Button
            type="submit"
            label="注册"
            icon="pi pi-user-plus"
            :loading="loading"
            class="w-full mt-10"
          />
        </form>
      </div>
    </Dialog>
  </div>
</template>

<style scoped>
::v-deep(.p-password-input) {
  width: 100% !important;
}

.p-error {
  color: red;
  padding-top: 8px;
  padding-bottom: 8px;
}
</style>
